package com.study.leetcode;

public class Solution_67 {
    public static String addBinary(String num1, String num2) {
        StringBuilder stringBuilder = new StringBuilder();
        int dif = Math.abs(num1.length() - num2.length());
        if (num1.length() < num2.length()) {
            String temp = num1;
            num1 = num2;
            num2 = temp;
        }
        boolean f = false;
        for (int i = num1.length() - 1; i >= 0; i--) {
            char c1 = num1.charAt(i);
            int index = i - dif;
            //如果在范围内则取值，否则相当于前置补0
            int c2 = (0 <= index && index < num2.length()) ? num2.charAt(index) - '0' : 0;
            char add = (char) (c1 + c2 + (f ? 1 : 0));
            f = false;
            if (add > '1') {
                add = (char) (add - 2);
                f = true;
            }
            stringBuilder.append(add);
        }
        if (f) {
            stringBuilder.append("1");
        }
        return stringBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        String s = addBinary("1", "101");
        System.out.println("s = " + s);
    }

}
